import java.util.*;

public class Solution2192 {
    public List<List<Integer>> getAncestors(int n, int[][] edges) {
        List<List<Integer>> reach=new ArrayList<>();
        List<Set<Integer>> temp=new ArrayList<>();
        List<List<Integer>> ans=new ArrayList<>();
        for (int i=0;i<n;i++){
            temp.add(new HashSet<>());
            reach.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            reach.get(edge[0]).add(edge[1]);
        }
        int[] du=new int[n];
        for (int[] edge : edges) {
            du[edge[1]]++;
        }
        Queue<Integer> queue=new LinkedList<>();
        for (int i = 0; i < n; i++) {
            if (du[i]==0){
                queue.offer(i);
            }
        }
        while (!queue.isEmpty()){
            int t=queue.poll();
            List<Integer> r=reach.get(t);
            for (Integer integer : r) {
                Set<Integer> list=temp.get(integer);
                list.addAll(temp.get(t));
                list.add(t);
                du[integer]--;
                if (du[integer]==0){
                    queue.offer(integer);
                }
            }

        }
        for (int i=0;i<n;i++){
            ans.add(new ArrayList<>(temp.get(i)));
            ans.get(i).sort(Comparator.comparingInt(a -> a));
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution2192().getAncestors(8,new int[][]{{0,3},{0,4},{1,3},{2,4},{2,7},{3,5},{3,6},{3,7},{4,6}}));

    }
}
